package com.rjkj.medicalwaste.ui.blue

import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.content.*
import android.os.Bundle
import android.util.Log
import android.view.*
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.activityViewModels
import androidx.fragment.app.viewModels
import androidx.lifecycle.Observer
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.LinearLayoutManager
import com.inuker.bluetooth.library.Constants
import com.inuker.bluetooth.library.connect.listener.BleConnectStatusListener
import com.inuker.bluetooth.library.connect.options.BleConnectOptions
import com.inuker.bluetooth.library.utils.BluetoothUtils
import com.rjkj.medicalwaste.MainActivity
import com.rjkj.medicalwaste.R
import com.rjkj.medicalwaste.adapter.BluetoothDeviceAdapter
import com.rjkj.medicalwaste.adapter.ItemClick
import com.rjkj.medicalwaste.base.BaseFragment
import com.rjkj.medicalwaste.bean.BleDeviceBean
import com.rjkj.medicalwaste.bean.BlueConnectResult
import com.rjkj.medicalwaste.bluetooth.BluetoothSPP
import com.rjkj.medicalwaste.bluetooth.BluetoothState
import com.rjkj.medicalwaste.databinding.FragmentBluetoothListBinding
import com.rjkj.medicalwaste.livedatabus.LiveDataBus
import com.rjkj.medicalwaste.utils.AppPrefsUtils
import com.rjkj.medicalwaste.utils.BaseConstant
import com.rjkj.medicalwaste.utils.BlueManager
import com.rjkj.medicalwaste.utils.ClientManager
import com.rjkj.medicalwaste.viewmodels.BluetoothControlViewModel
import com.rjkj.medicalwaste.viewmodels.BluetoothDeviceViewModel


class BluetoothListFragment : BaseFragment<FragmentBluetoothListBinding>() {
    private val bluetoothListModel: BluetoothDeviceViewModel by viewModels()
    private val bluetoothControlViewModel: BluetoothControlViewModel by activityViewModels()

    lateinit var mBtAdapter: BluetoothAdapter
    private val listAdapter = BluetoothDeviceAdapter(object : ItemClick<BleDeviceBean> {
        override fun onClicked(view: View, value: BleDeviceBean) {
            Log.e(TAG, "onClicked: ${value.address}")
            connectToDevice(value)
        }
    })
    private val mReceiver: BroadcastReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            val action = intent.action
            Log.e(TAG, "onReceive")
            when {
                BluetoothDevice.ACTION_FOUND == action -> {
                    val device =
                        intent.getParcelableExtra<BluetoothDevice>(BluetoothDevice.EXTRA_DEVICE)
                    if (device != null && device.name != null) {
                        listAdapter.addData(BleDeviceBean(
                            device.name, device.address
                        ).also {
                            Log.e(TAG, "onDeviceFounded: ${it.toString()}")
                        })
                    }
                }
                BluetoothAdapter.ACTION_DISCOVERY_FINISHED == action -> {
                    bluetoothListModel.scanning.value = false
                    showTip("搜索结束")
                }
                BluetoothAdapter.ACTION_DISCOVERY_STARTED == action -> {
                    listAdapter.cleanData()
                    bluetoothListModel.scanning.value = true
                    showTip("搜索开始")
                }
            }
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {

        val binding = FragmentBluetoothListBinding.inflate(inflater, container, false)
        binding.lifecycleOwner = viewLifecycleOwner
        onSubscribeUi(binding)
        // Register for broadcasts when discovery has finished
        mBtAdapter = BluetoothAdapter.getDefaultAdapter()
        // Register for broadcasts when discovery has finished
        val filter = IntentFilter()
        filter.apply {
            addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)
            addAction(BluetoothDevice.ACTION_FOUND)
            addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED)
        }
        requireActivity().registerReceiver(mReceiver, filter)
        return binding.root
    }

    override fun onDestroyView() {
        //取消搜索
        if (mBtAdapter.isDiscovering) {
            mBtAdapter.cancelDiscovery()
        }
        requireActivity().unregisterReceiver(mReceiver)
        super.onDestroyView()
    }


    override fun onSubscribeUi(binding: FragmentBluetoothListBinding) {
        LiveDataBus.get().with(MainActivity.SCAN_DATA, String::class.java).observe(
            viewLifecycleOwner, Observer {
//            showTip(it)
//            Log.e(TAG, "FragmentBluetoothListBinding: $it", )
            }
        )
        binding.deviceList.apply {
            layoutManager = LinearLayoutManager(context)
            adapter = listAdapter
        }
        bluetoothListModel.scanning.observe(viewLifecycleOwner, Observer {
            val appCompatActivity = activity as AppCompatActivity
            appCompatActivity.invalidateOptionsMenu()
        })
        val appCompatActivity = requireActivity() as AppCompatActivity
        appCompatActivity.setSupportActionBar(binding.toolbar)
        binding.toolbar.setNavigationOnClickListener {
            Log.e(TAG, "Navigation: ")
            findNavController().navigateUp()
        }
        setHasOptionsMenu(true)

//        ClientManager.client?.registerConnectStatusListener(mDevice.getAddress(), mConnectStatusListener);
    }

    override fun onPrepareOptionsMenu(menu: Menu) {
        val value = bluetoothListModel.scanning.value
        if (value != null) {
            menu.findItem(R.id.refresh).isVisible = !value
            menu.findItem(R.id.cancel).isVisible = value
        } else {
            menu.findItem(R.id.refresh).isVisible = true
            menu.findItem(R.id.cancel).isVisible = false
        }
        super.onPrepareOptionsMenu(menu)
    }

    override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
        inflater.inflate(R.menu.toolbar_menu, menu)
        val value = bluetoothListModel.scanning.value
        if (value != null) {
            menu.findItem(R.id.refresh).isVisible = !value
            menu.findItem(R.id.cancel).isVisible = value
        } else {
            menu.findItem(R.id.refresh).isVisible = true
            menu.findItem(R.id.cancel).isVisible = false
        }

    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {
            R.id.cancel -> {
                closeSearchDevice()
                return true
            }
            R.id.refresh -> {
                searchDevice()
                return true
            }
//            R.id.test -> {
//                findNavController().navigate(R.id.action_bluetoothListFragment_to_deviceDataTestFragment)
//                return true
//            }
        }
        return super.onOptionsItemSelected(item)
    }

    private fun connectToDevice(value: BleDeviceBean) {
        val mDevice: BluetoothDevice = BluetoothUtils.getRemoteDevice(value.address) ?: return
        //TODO(加一个弹窗)
        val builder = AlertDialog.Builder(requireContext())
        builder
            .setTitle("是否连接蓝牙：${mDevice.name}")
            .setNegativeButton("取消") { _: DialogInterface, _: Int ->
            }
            .setPositiveButton("确定") { _: DialogInterface, _: Int ->
                bluetoothControlViewModel.bluetoothTry.value =
                    BlueConnectResult(value.address, mDevice.type)
            }
            .show()
//        val options = BleConnectOptions.Builder()
//            .setConnectRetry(3)
//            .setConnectTimeout(20000)
//            .setServiceDiscoverRetry(3)
//            .setServiceDiscoverTimeout(10000)
//            .build()
//
//
//        when (mDevice.type) {
//            BluetoothDevice.DEVICE_TYPE_CLASSIC -> {
//                Log.e(TAG, "DEVICE_TYPE_CLASSIC: ")
//                //TODO(加一个弹窗)
//                val builder = AlertDialog.Builder(requireContext())
//                builder
//                    .setTitle("是否连接蓝牙：${mDevice.name}")
//                    .setNegativeButton("取消") { _: DialogInterface, _: Int ->
//                    }
//                    .setPositiveButton("确定") { _: DialogInterface, _: Int ->
////                        BlueManager.instance.blue.apply {
////                            if (serviceState == BluetoothState.STATE_CONNECTED) {
////                                if (connectedDeviceAddress.equals(mDevice.address)) {
////                                    showTip("已经连接了该设备")
////                                    return@setPositiveButton
////                                } else {
////                                    disconnect()
////                                }
////                            }
////                            //如果是已经绑定的设备
////                            val pairedDevices = mBtAdapter.bondedDevices
////                            if (pairedDevices.size > 0) {
////                                for (bdevice in pairedDevices) {
////                                    if (bdevice.address == mDevice.address) {
////                                        connect(bdevice.address)
////                                        return@setPositiveButton
////                                    }
////                                }
////                            }
////                            connect(mDevice.address)
////                        }
//
//                    }
//                    .show()
//
//
//            }
//            BluetoothDevice.DEVICE_TYPE_LE -> {
//                Log.e(TAG, "DEVICE_TYPE_LE: ")
//                //TODO(加一个弹窗)
//                val builder = AlertDialog.Builder(requireContext())
//                builder
//                    .setTitle("是否连接蓝牙：${mDevice.name}")
//                    .setNegativeButton("取消") { _: DialogInterface, _: Int ->
//                    }
//                    .setPositiveButton("确定") { _: DialogInterface, _: Int ->
//                        ClientManager.client?.registerConnectStatusListener(
//                            mDevice.address,
//                            mBleConnectStatusListener
//                        )
//                        ClientManager.client?.connect(mDevice.address, options) { code, _ ->
//                            if (code == 0) {
//                                showTip("连接成功")
//                                AppPrefsUtils.putString(BaseConstant.BLUETOOTH_MAC, mDevice.address)
//                            }
//                            Log.e(TAG, "onResponse:$code ")
//
//                        }
//                    }
//                    .show()
//            }
//            BluetoothDevice.DEVICE_TYPE_DUAL -> {
//                Log.e(TAG, "DEVICE_TYPE: " + mDevice.type)
//                ClientManager.client?.connect(mDevice.address, options) { code, _ ->
//                    if (code == 0) {
//                        showTip("连接成功")
//                        AppPrefsUtils.putString(BaseConstant.BLUETOOTH_MAC, mDevice.address)
//                    }
//                    Log.e(TAG, "onResponse:$code ")
//                }
//            }
//        }


    }

    private fun closeSearchDevice() {
//        ClientManager.client?.stopSearch()
        mBtAdapter.cancelDiscovery()
    }

    private fun searchDevice() {
        if (BlueManager.instance.blue.serviceState == BluetoothState.STATE_CONNECTING)
            BlueManager.instance.blue.disconnect() //保证断开之前设备的连接
        mBtAdapter.startDiscovery()
    }


}